<script setup>
import { ref, nextTick, defineEmits } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import ProjectApi from '@/service/api/project/project'
import MyApi from '@/service/api/my/my'
const formRef = ref()
const drawerVisibility = ref(false)

const formModel = ref({
  title: '',
  info: '',
  people_num: '',
  start_time: '',
  over_time: '',
  categorization: ''
})
const defaultForm = {
  title: '',
  info: '',
  people_num: '',
  start_time: '',
  over_time: '',
  categorization: ''
}
const editorContent = ref()

// drawer 抽屉显示
const open = async (row) => {
  if (row.project_id) {
    drawerVisibility.value = true
    formModel.value = { ...row }
    nextTick(() => {
      editorContent.value.setHTML(formModel.value.info)
    })
  } else {
    const res = await MyApi.getMyInfo()
    if (res.data.phone_num === null || res.data.qq === null) {
      dialogTableVisible.value = true
    } else {
      drawerVisibility.value = true
      formModel.value = { ...defaultForm }
      nextTick(() => {
        editorContent.value.setHTML('')
      })
    }
  }
}

// 发布编辑  提交按钮
const emit = defineEmits(['success'])
const dialogTableVisible = ref(false)
const handleSubmit = async () => {
  await formRef.value.validate()
  ElMessageBox.confirm('确认提交该项目信息？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 把formModel里面的people_num转化为number整数类型
      formModel.value.people_num = parseInt(formModel.value.people_num)
      // 编辑
      if (formModel.value.project_id) {
        await ProjectApi.editProject(formModel.value)
        ElMessage.success('编辑成功')
        drawerVisibility.value = false
        emit('success', 'edit')
      } else {
        // 添加
        await ProjectApi.publishProject(formModel.value)
        ElMessage.success('添加成功')
        drawerVisibility.value = false
        emit('success', 'add')
      }
    })
    .catch(() => {
      ElMessage.fail('操作失败')
    })
}
// 是否为继续发布项目
const handleContinuePublish = () => {
  dialogTableVisible.value = false
  drawerVisibility.value = true
  formModel.value = { ...defaultForm }
  nextTick(() => {
    editorContent.value.setHTML('')
  })
}
// 表单检验
const rules = {
  title: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  start_time: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  over_time: [{ required: true, message: '请选择截止时间', trigger: 'blur' }],
  people_num: [
    { required: true, message: '请输入报名人数', trigger: 'blur' },
    // 必须是整数
    {
      validator: (rule, value, callback) => {
        const numberValue = parseInt(value)
        if (isNaN(numberValue) || numberValue.toString() != value) {
          callback(new Error('请输入整数'))
        } else {
          callback() // 验证通过
        }
      },
      trigger: 'blur'
    }
  ],
  info: [{ required: true, message: '请输入项目内容', trigger: 'blur' }],
  categorization: [{ required: true, message: '请选择项目分类', trigger: 'blur' }]
}
// 富文本编辑器
const editorOption = ref({
  placeholder: '请在这里输入',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
      [{ list: 'ordered' }, { list: 'bullet' }], //列表
      [{ script: 'sub' }, { script: 'super' }], // 上下标
      [{ indent: '-1' }, { indent: '+1' }], // 缩进
      [{ direction: 'rtl' }], // 文本方向
      [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
      [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
      [{ font: [] }], //字体
      ['image', 'video'] //上传图片、上传视频
    ]
  }
})
// 项目分类选择
const options = [
  {
    value: 0,
    label: '全体'
  },
  {
    value: 1,
    label: '计院'
  },
  {
    value: 2,
    label: '理学院'
  },
  {
    value: 3,
    label: '管院'
  }
]
const lookContent = () => {
  console.log(formModel.value.content)
}
defineExpose({ open })
</script>
<template>
  <el-drawer
    v-model="drawerVisibility"
    :title="formModel.project_id ? '编辑项目' : '添加项目'"
    direction="rtl"
    size="45%"
  >
    <el-form
      :model="formModel"
      ref="formRef"
      label-width="100px"
      class="drawer-form"
      :rules="rules"
    >
      <el-form-item label="项目名称" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入项目名称"></el-input>
      </el-form-item>
      <el-form-item label="项目分类" prop="categorization">
        <el-select
          v-model="formModel.categorization"
          placeholder="请选择项目分类"
          size="default"
          value-key="id"
          style="width: 450px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报名人数" prop="people_num">
        <el-input v-model="formModel.people_num" placeholder="请输入报名人数"></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="start_time">
        <el-date-picker
          v-model="formModel.start_time"
          type="datetime"
          placeholder="请选择开始时间"
          format="YYYY-MM-DD hh:mm:ss"
          value-format="YYYY-MM-DD h:m:s"
        />
      </el-form-item>
      <el-form-item label="截止时间" prop="over_time">
        <el-date-picker
          v-model="formModel.over_time"
          type="datetime"
          placeholder="请选择截止时间"
          format="YYYY-MM-DD hh:mm:ss"
          value-format="YYYY-MM-DD h:m:s"
        />
      </el-form-item>
      <el-form-item label="项目内容" prop="info" @click="lookContent">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="formModel.info"
            contentType="html"
            :options="editorOption"
            ref="editorContent"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="drawerVisibility = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
  <el-dialog
    v-model="dialogTableVisible"
    title="您的个人信息尚未完善，请选择您的操作"
    width="600"
    center
    align-center
  >
    <div class="dialog-footer">
      <el-button type="primary" @click="$router.push('/info')">完善个人信息</el-button>
      <el-button type="primary" @click="handleContinuePublish">继续发布项目</el-button>
    </div>
  </el-dialog>
</template>
<style scoped lang="scss">
.editor {
  width: 700px;
  height: 300px;
  margin-bottom: 100px;
}

:deep(.el-input) {
  width: 450px;
}
.dialog-footer {
  display: flex;
  justify-content: space-evenly;
  .el-button {
    margin-top: 20px;
  }
}
</style>
